package com.rc.saas.tenant.controller.ticket;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.ticket.RcCouponTemplateApply;
import com.rc.saas.tenant.search.operator.CouponApplySearch;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.ticket.RcCouponTemplateApplyService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.tenant.TenantUserRoleVo;
import com.rc.saas.tenant.vo.ticket.CouponTemplateApplyVo;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Controller
@RequestMapping("/coupon/apply")
public class CouponApplyController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RcCouponTemplateApplyService couponTemplateApplyService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Autowired
    private RcOperatorService operatorService;

    /**
     * 卡券申请
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        if ("1".equals(user.getUserType())) {
            model.addAttribute("operatorId", user.getOperatorId());
        }
        return "/templates/ticket/couponApply";
    }

    /**
     * 卡券申请(加盟商 )
     * @param model
     * @return
     */
    @RequestMapping(value = "/couponApplyWithOperator", method = RequestMethod.GET)
    public String couponApplyWithOperator(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        if ("1".equals(user.getUserType())) {
            model.addAttribute("operatorId", user.getOperatorId());
        }
        return "/templates/ticket/couponApplyWithOperator";
    }


    @ResponseBody
    @RequestMapping(value = "/listPageCouponApply", method = RequestMethod.GET)
    public WebPageInfo listPageCouponApply(CouponApplySearch search) {
        TenantUser user = ShiroUtils.getSessionUser();
        search.setLoginName(user.getLoginName());
        PageInfo pageInfo = couponTemplateApplyService.listPageCouponApply(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    @RequestMapping(value = "/add/{operatorId}", method = RequestMethod.GET)
    public String add(Model model, @PathVariable("operatorId") Long operatorId) {
        model.addAttribute("operatorId", operatorId);
        return "/templates/ticket/addCouponApply";
    }

    @ResponseBody
    @RequestMapping(value = "/updateCouponApplyForAudit", method = RequestMethod.POST)
    public TResponse updateCouponApplyForAudit(Long id, String status) {
        RcCouponTemplateApply couponTemplateApply = couponTemplateApplyService.selectByPrimaryKey(id);
        couponTemplateApply.setApplyStatus(status);
        couponTemplateApplyService.updateByPrimaryKeySelective(couponTemplateApply);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteCouponApply", method = RequestMethod.POST)
    public TResponse deleteCouponApply(Long id) {
        couponTemplateApplyService.deleteByPrimaryKey(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/addCouponApply", method = RequestMethod.POST)
    public TResponse addCouponApply(RcCouponTemplateApply couponTemplateApply) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUserRoleVo userRoleVo =  tenantRoleService.getLonginRole(user.getLoginName());
        if (StringUtils.equals("2",userRoleVo.getRoleType())){
            RcOperator operator = operatorService.selectMobile(user.getLoginName());
            couponTemplateApply.setOperatorId(operator.getOperatorId());
        }
        couponTemplateApplyService.insertSelective(couponTemplateApply);
        return TResponse.SUCCESS();
    }

    /**
     * 导出卡券申请列表数据
     */
    @ResponseBody
    @RequestMapping("/exporListPageCouponApply")
    public TResponse exporListPageCouponApply(Long operatorId, String operatorName,
                                              @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                              @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        CouponApplySearch search = new CouponApplySearch();
        search.setOperatorId(operatorId);
        search.setOperatorName(operatorName);
        search.setOffset(pageNo);
        search.setLimit(pageSize);
        try {
            PageInfo pageInfo = couponTemplateApplyService.listPageCouponApply(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("卡券申请列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), CouponTemplateApplyVo.class).sheet("卡券申请列表").doWrite(pageInfo.getList());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

}
